package com.kenliang.netty.rpc.parallel;

import org.apache.commons.lang3.StringUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author KenLiang
 * @description:
 * @date Created in 6:43 PM 2019/3/26.
 */
public class NamedThreadFactory implements ThreadFactory {


    private final String prefix;

    private final AtomicInteger threadNum = new AtomicInteger(1);

    private final boolean isDaemon;

    private final ThreadGroup threadGroup;


    public NamedThreadFactory(String prefix) {
        this(prefix,false);
    }

    public NamedThreadFactory(String prefix, boolean isDaemon) {
        this.prefix = StringUtils.isNotBlank(prefix)?prefix:"netty-rpc";
        this.isDaemon = isDaemon;
        // todo 安全管理器学习，demo使用  （根据是否有安全管理器，获取threadGroup的方式不一样？？？）
//        SecurityManager securityManager = System.getSecurityManager();
//        threadGroup = (securityManager == null) ? Thread.currentThread().getThreadGroup() : securityManager.getThreadGroup();
        this.threadGroup = Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        String name = this.prefix+"-thread-"+this.threadNum;
        Thread thread = new Thread(this.threadGroup,r,name,0);
        thread.setDaemon(this.isDaemon);
        return thread;
    }
}
